package com.enzism.springboot.quartz.service.impl;


import com.enzism.springboot.quartz.model.JobEntity;
import com.enzism.springboot.quartz.job.HelloJob;
import com.enzism.springboot.quartz.result.SifarResult;
import com.enzism.springboot.quartz.service.QuartzManagerService;
import org.quartz.*;
import org.quartz.impl.matchers.GroupMatcher;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Service
public class QuartzManagerServiceImpl implements QuartzManagerService {
    @Autowired
    private Scheduler scheduler;// 获取调度器

    @Override
    public SifarResult addJob(JobEntity jobEntity, Class jobClass) {
        try {
            //Class cls=Class.forName(jobEntity.getClazz());
            //System.out.println(cls.getName());
            // 创建一项作业
            JobDetail job = JobBuilder.newJob(jobClass)
                    .withIdentity(jobEntity.getJobName(), jobEntity.getGroupName())
                    .build();

            /*==========Start===========================================================*/
            //方法一
            job.getJobDataMap().put("message", jobEntity.getJobName());
            //方法二
            //scheduler.getContext().put("com.test.controller.JobController", jobController);
            /*===========End==========================================================*/

            // 创建一个触发器
            CronTrigger trigger = TriggerBuilder.newTrigger()
                    .withIdentity(jobEntity.getJobName(), jobEntity.getGroupName())
                    .withSchedule(CronScheduleBuilder.cronSchedule(jobEntity.getCronExpr()))
                    .build();
            // 告诉调度器使用该触发器来安排作业
            scheduler.scheduleJob(job, trigger);


            /*========Start=============================================================*/
            // 创建并注册一个全局的Job Listener
            //scheduler.getListenerManager().addJobListener(new SimpleJobListener(), EverythingMatcher.allJobs());
            // 创建并注册一个指定任务的Job Listener
            //scheduler.getListenerManager().addJobListener(new SimpleJobListener(),KeyMatcher.keyEquals(JobKey.jobKey(jobEntity.getJobName(), jobEntity.getJobGroupName())));
            /*========End=============================================================*/

            /*=====Start================================================================*/
            // 创建并注册一个全局的Trigger Listener
            //scheduler.getListenerManager().addTriggerListener(new SimpleTriggerListener("SimpleTrigger"), EverythingMatcher.allTriggers());

            // 创建并注册一个局部的Trigger Listener
            //scheduler.getListenerManager().addTriggerListener(new SimpleTriggerListener("SimpleTrigger"), KeyMatcher.keyEquals(TriggerKey.triggerKey(jobEntity.getTriggerName(), jobEntity.getTriggerGroupName())));

            /*=======End==============================================================*/
            // 启动
            if(!scheduler.isShutdown()){
                scheduler.start();
            }
        }catch (Exception e) {
            throw new RuntimeException(e);
        }

        return SifarResult.success();
    }

    @Override
    public SifarResult getJobList() {
        List<JobEntity> jobInfos = new ArrayList<JobEntity>();

        try {
            List<String> triggerGroupNames = scheduler.getTriggerGroupNames();
            for (String triggerGroupName : triggerGroupNames) {
                Set<TriggerKey> triggerKeySet = scheduler.getTriggerKeys(GroupMatcher
                        .triggerGroupEquals(triggerGroupName));
                for (TriggerKey triggerKey : triggerKeySet) {
                    Trigger t = scheduler.getTrigger(triggerKey);
                    if (t instanceof CronTrigger) {
                        CronTrigger trigger = (CronTrigger) t;
                        JobKey jobKey = trigger.getJobKey();
                        JobDetail jd = scheduler.getJobDetail(jobKey);
                        JobEntity jobInfo = new JobEntity();
                        jobInfo.setJobName(jobKey.getName());
                        jobInfo.setGroupName(jobKey.getGroup());
                        jobInfo.setCronExpr(trigger.getCronExpression());
                        jobInfo.setNextFireTime(trigger.getNextFireTime());
                        jobInfo.setPreviousFireTime(trigger.getPreviousFireTime());
                        jobInfo.setStartTime(trigger.getStartTime());
                        jobInfo.setEndTime(trigger.getEndTime());
                        jobInfo.setJobClass(jd.getJobClass().getCanonicalName());
                        // jobInfo.setDuration(Long.parseLong(jd.getDescription()));
                        Trigger.TriggerState triggerState = scheduler.getTriggerState(trigger.getKey());
                        jobInfo.setJobStatus(triggerState.toString());

                        jobInfos.add(jobInfo);
                    }
                }
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
        return SifarResult.success(jobInfos);
    }

    @Override
    public void deleteJob(String jobName, String groupName) {

        try {

            JobKey jobKey=JobKey.jobKey(jobName, groupName);
            TriggerKey triggerKey=TriggerKey.triggerKey(jobName, groupName);
            // 停止触发器
            scheduler.pauseTrigger(triggerKey);
            // 移除触发器
            scheduler.unscheduleJob(triggerKey);
            // 删除任务
            scheduler.deleteJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void resumeJob(String jobName, String groupName) {
        try {
            JobKey jobKey=JobKey.jobKey(jobName, groupName);
            scheduler.resumeJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void pauseJob(String jobName, String groupName) {
        try {
            JobKey jobKey=JobKey.jobKey(jobName, groupName);
            scheduler.pauseJob(jobKey);
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void editJob(JobEntity jobEntity) {
        TriggerKey oldTriggerKey=TriggerKey.triggerKey(jobEntity.getOldjobName(), jobEntity.getOldGroupName());
        JobKey jobKey=JobKey.jobKey(jobEntity.getOldjobName(), jobEntity.getOldGroupName());
        try {
            CronTrigger trigger = (CronTrigger) scheduler.getTrigger(oldTriggerKey);
            if(trigger!=null){
                JobDetail jobDetail=scheduler.getJobDetail(jobKey);
                // 停止触发器
                scheduler.pauseTrigger(oldTriggerKey);
                // 移除触发器
                scheduler.unscheduleJob(oldTriggerKey);
                // 删除任务
                scheduler.deleteJob(jobKey);
                //启动编辑后的任务
                this.addJob(jobEntity, HelloJob.class);
            }
        } catch (SchedulerException e) {
            e.printStackTrace();
        }
    }
}
